package shop.core.plugins.bmap;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description  调用百度地图api转换物理地址
 * http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
 * @Author semstouch
 * @Date 2017/9/6
 **/
public class BaiduMap {
    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(BaiduMap.class);

    public static void main(String[] args) {
        geoconv("24.486494","118.178825");
    }
    /**
     * @Description 根据经纬度获取实际的地理位置
     * @param lng 经度
     * @param lat 维度
     * @throws MalformedURLException
     * @throws IOException
     */
    public static String getLatlon(String lat,String lng){
        try{
            String address = "http://api.map.baidu.com/geocoder/v2/?extensions_poi=null&location="+lat+","+lng+"&output=json&ak=DstSYhzzZEadsqN24e3pwkaquazEQt4E";
            URL t = new URL(address);
            URLConnection conn = t.openConnection();
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = reader.readLine();
            ObjectMapper mapper = new ObjectMapper();
            Map res=mapper.readValue(line, Map.class);
            Map result=(Map)res.get("result");
            String formatted_address=result.get("formatted_address").toString();
            return  formatted_address;
        }catch (Exception e){
            logger.error(e.toString());
        }
        return  null;
    }

    /**
     * GPS坐标转化成百度坐标
     * @param lat
     * @param lng
     * @return
     */
    public  static Map geoconv(String lat,String lng){
        Map resMap= new HashMap();
        try{
            String address = "http://api.map.baidu.com/geoconv/v1/?coords="+lng+","+lat+"&from=1&to=5&ak=DstSYhzzZEadsqN24e3pwkaquazEQt4E";
            URL t = new URL(address);
            URLConnection conn = t.openConnection();
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = reader.readLine();
            ObjectMapper mapper = new ObjectMapper();
            Map res=mapper.readValue(line, Map.class);
            List result=(List)res.get("result");
            resMap=(Map) result.get(0);
            return  resMap;
        }catch (Exception e){
            logger.error(e.toString());
        }
        return  null;
    }
}
